import "./reset.css";
import dayjs from "dayjs";
import editForm from "../form/index.vue";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { ElMessageBox } from "element-plus";
import { computed, onMounted, reactive, ref, type Ref, h } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import type { FormItemProps } from "./types";

// 显式导出 useChannelMembers 函数
export function useChannelMembers(tableRef: Ref) {
  const form = reactive({
    channelId: "",
    tenantId: "",
    SearchTerm: "",
    OrderBy: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const channelOptions = ref([]);
  const tenantOptions = ref([]);
  const higherDeptOptions = ref([]);

  const columns: TableColumnList = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "ID",
      prop: "id",
      width: 90
    },
    {
      label: "频道ID",
      prop: "channelId",
      width: 90
    },
    {
      label: "频道名称",
      prop: "channelName",
      minWidth: 130
    },
    {
      label: "用户ID",
      prop: "userId",
      width: 90
    },
    {
      label: "用户名称",
      prop: "userName",
      minWidth: 130
    },
    {
      label: "优先级",
      prop: "priority",
      width: 90,
      cellRenderer: scope => (
        <span style={{ color: getPriorityColor(scope.row.priority) }}>
          {scope.row.priority}级
        </span>
      )
    },
    {
      label: "租户ID",
      prop: "tenantId",
      width: 90
    },
    {
      label: "租户名称",
      prop: "tenantName",
      minWidth: 130
    },
    {
      label: "经销商ID",
      prop: "dealerId",
      width: 90
    },
    {
      label: "经销商名称",
      prop: "dealerName",
      minWidth: 130
    },
    {
      label: "加入时间",
      prop: "joinTime",
      minWidth: 180,
      cellRenderer: scope => (
        <span>{dayjs(scope.row.joinTime).format("YYYY-MM-DD HH:mm:ss")}</span>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });

  // 获取优先级颜色
  function getPriorityColor(priority) {
    if (priority <= 3) return "#1bbf1b";
    if (priority <= 6) return "#ffa500";
    return "#e74242";
  }

  // 加载频道列表
  function loadChannelOptions() {
    http
      .post(changeHttpLink("index.php/channel/channel/list"), {
        data: {}
      })
      .then((res: any) => {
        if (res.Success) {
          channelOptions.value = res.Data.Items;
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
  }

  // 加载租户列表
  function loadTenantOptions() {
    http
      .post(changeHttpLink("index.php/tenant/tenant/list"), {
        data: {}
      })
      .then((res: any) => {
        if (res.Success) {
          tenantOptions.value = res.Data.Items;
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
  }

  // 搜索频道成员
  function onSearch() {
    loading.value = true;

    const params = {
      ...form,
      PageIndex: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    http
      .post(changeHttpLink("index.php/channelMembers/channelMembers/list"), {
        data: params
      })
      .then((res: any) => {
        if (res.Success) {
          dataList.value = res.Data.Items || [];
          pagination.total = res.Data.TotalCount || 0;
        } else {
          message(res.Message, { type: "error" });
          dataList.value = [];
          pagination.total = 0;
        }
        loading.value = false;
      })
      .catch(err => {
        message(err.message, { type: "error" });
        dataList.value = [];
        pagination.total = 0;
        loading.value = false;
      });
  }

  // 重置表单
  function resetForm(formRef) {
    formRef.resetFields();
    onSearch();
  }

  // 批量删除
  function onbatchDel() {
    const selectedRows = tableRef.value.getSelectionRows();
    if (selectedRows.length === 0) {
      message("请选择要删除的成员", { type: "warning" });
      return;
    }

    ElMessageBox.confirm(
      `确认要删除选中的${selectedRows.length}个成员吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        const ids = selectedRows.map(row => row.id);

        http
          .post(
            changeHttpLink(
              "index.php/channelMembers/channelMembers/batch_delete"
            ),
            {
              data: { ids }
            }
          )
          .then((res: any) => {
            if (res.Success) {
              message(`成功删除${selectedRows.length}个成员`, {
                type: "success"
              });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 打开对话框
  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}频道成员`,
      props: {
        formInline: {
          title,
          higherDeptOptions: higherDeptOptions.value,
          ...row
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(
            `您${title}了频道成员名称为${curData.form.userName || curData.form.channelName}的这条数据`,
            {
              type: "success"
            }
          );
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              chores();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              chores();
            }
          }
        });
      }
    });
  }

  // 处理更新
  function handleUpdate(row) {
    console.log(row);
  }

  // 处理删除
  function handleDelete(row) {
    ElMessageBox.confirm(
      `确认要删除成员ID为${row.id}的这条数据吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        http
          .post(
            changeHttpLink("index.php/channelMembers/channelMembers/delete"),
            {
              data: { id: row.id }
            }
          )
          .then((res: any) => {
            if (res.Success) {
              message(`成功删除成员ID为${row.id}的数据`, { type: "success" });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 处理分页大小变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    dataList.value = [];
    onSearch();
  }

  // 处理当前页码变化
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 处理选择变化
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  // 取消选择
  function onSelectionCancel() {
    tableRef.value.clearSelection();
  }

  // 设备检测
  function deviceDetection() {
    return window.innerWidth < 1200;
  }

  // 挂载时加载数据
  onMounted(() => {
    loadChannelOptions();
    loadTenantOptions();
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    channelOptions,
    tenantOptions
  };
}
